//
//  AirConditionalView.swift
//  xgwjinterconnection
//  空调页面
//  Created by WangWeiShuo on 2025/8/19.
//

import SwiftUI
import Combine

struct AirConditionalView: View {
    @Environment(\.dismiss) var dismiss
    
    let windModeItem = [
        SegmentImageItem(iconNormal: "icon_wind_fh",iconPressed: "icon_wind_fh_pressed",selectionIndex: 0),
        SegmentImageItem(iconNormal: "icon_wind_hb",iconPressed: "icon_wind_hb_pressed",selectionIndex: 1),
        SegmentImageItem(iconNormal: "icon_wind_fhb",iconPressed: "icon_wind_fhb_pressed",selectionIndex: 2),
        SegmentImageItem(iconNormal: "icon_wind_foot",iconPressed: "icon_wind_foot_pressed",selectionIndex: 3)
    ]
    
    //吹风模式，0:吹面+除霜，1:吹面+吹背，2:吹面+吹背+吹脚，3：吹脚模式
    @State private var windMode = 0
    //开关，1：打开，0:关闭
    @State private var airOpen = 0
    //吹风强度
    @State private var windStrength = 0
    // 选中的温度单位，0:摄氏度，1:华氏度
    @State private var selectedUnit = TemperatureUnit.celsius
    //空调类型,0:电装，1:泰伯
    @State private var airType = 0
    //循环模式，0:内循环，1:外循环
    @State private var loopMode = 0
    //自动模式，0:关闭自动，1:开启自动
    @State private var autoMode = 0
    //压缩机，0:关闭，1:开启
    @State private var compressor = 0
    
    @StateObject private var socketManager = SocketManager.shared
    @State private var cancellables = Set<AnyCancellable>()
    // 用于存储定时器订阅
    @State private var cancellable: AnyCancellable?
    // 控制定时器状态
    @State private var isRunning: Bool = false
    
    @State private var airInfo: AirInfoBean?
    
    var body: some View {
        
        VStack(){
            WikaNavigationView(showBackIcon: true, title: NSLocalizedString("air_title", comment: "空调"),onBack: {
                dismiss() }).frame(maxHeight: 65)
            
            HStack(){
                Spacer()
                Image("icon_indoor_temp")
                    .resizable()
                    .scaledToFit()
                Text(airInfo?.indoortemperature ?? "22.5")
                Text("°C")
                
                Spacer()
                Spacer()
                
                Image("icon_indoor_temp")
                    .resizable()
                    .scaledToFit()
                Text(airInfo?.outdoortemperature ?? "22.5")
                Text("°C")
                Spacer()
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.top,-25)
            .padding(.horizontal)
            
            //吹风模式
            SegmentImageButton(selection: $windMode, items: windModeItem)
                .padding(.horizontal)
                .frame(height: 70)
                .onChange(of: windMode) { newValue in
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_WIND_MODE,value: UInt8(newValue))
                }
            
            HStack(){
                Button {
                    // 风量减按钮点击事件
                    print("风量减图标按钮被点击")
//                    if(windStrength > 0){
//                        windStrength = windStrength - 1
//                    }
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_AIR_VOLUME,value: 2)
                } label: {
                    Image(systemName: "minus")
                        .font(.largeTitle) // 控制图标大小
                        .foregroundColor(.gray) // 图标颜色
                        .padding() // 增加点击区域（可选）
                }
                
                Spacer()
                
                //风量
                WindStrengthView(strength: windStrength)
                
                Spacer()
                
                Button {
                    // 风量加按钮点击事件
                    print("风量加图标按钮被点击")
//                    if(windStrength < 6){
//                        windStrength = windStrength + 1
//                    }
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_AIR_VOLUME,value: 1)
                } label: {
                    Image(systemName: "plus")
                        .font(.largeTitle) // 控制图标大小
                        .foregroundColor(.gray) // 图标颜色
                        .padding() // 增加点击区域（可选）
                }
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.horizontal)
            
            HStack(){
                Button {
                    // 温度减按钮点击事件
                    print("温度减图标按钮被点击")
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_TEMPERATURE,value: 2)
                } label: {
                    Image("icon_temp_minus_normal")
                        .resizable()
                        .scaledToFit()
                        .font(.largeTitle) // 控制图标大小
                        .foregroundColor(.gray) // 图标颜色
                }
                
                Spacer()
                
                Text(airInfo?.curtemperature ?? "22.5").font(.largeTitle)
                Text("°C").font(.title3)
                
                Spacer()
                
                Button {
                    // 温度加按钮点击事件
                    print("温度加图标按钮被点击")
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_TEMPERATURE,value: 1)
                } label: {
                    Image("icon_temp_plus_normal")
                        .resizable()
                        .scaledToFit()
                        .foregroundColor(.gray) // 图标颜色
                }
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.horizontal)
            
            HStack(){
                //内外循环
                ToggleIconButton(iconNormal: "icon_int_circulate_pressed",iconPressed: "icon_ext_circulate_pressed",isPressed: loopMode == 0 ? false : true){
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_CYCLE_MODE,value: loopMode == 0 ? 1 : 0)
                }
                
                Spacer()
                
                //自动模式
                ToggleIconButton(iconNormal: "icon_auto_normal",iconPressed: "icon_auto_pressed",isPressed: autoMode == 0 ? false : true){
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_AUTO_MODE,value: autoMode == 0 ? 1 : 0)
                }
                
                Spacer()
                
                // 温度单位选择器
                Picker("温度单位", selection: $selectedUnit) {
                    ForEach(TemperatureUnit.allCases) { unit in
                        Text(unit.rawValue)
                            .background(Color.blue)
                    }
                }
                .tint(.blue)
                .pickerStyle(SegmentedPickerStyle()) // 使用分段控制器样式
                .padding(.horizontal)
                .frame(width: 120)
                .onChange(of: selectedUnit) { newValue in
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_AIR_UNIT,value: newValue == TemperatureUnit.celsius ? 1 : 0)
                }
                
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.horizontal)
            
            HStack(){
                Spacer()
                //开关
                ToggleIconButton(iconNormal: "icon_switch_normal",iconPressed: "icon_switch_pressed",isPressed: airOpen == 0 ? false : true){
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_AUTO_MODE,value: airOpen == 0 ? 1 : 0)
                }
                
                Spacer()
                //制冷压缩
                ToggleIconButton(iconNormal: "icon_refrigeration_normal",iconPressed: "icon_refrigeration_pressed",isPressed: compressor == 0 ? false : true){
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_AUTO_MODE,value: compressor == 0 ? 1 : 0)
                }
                
                Spacer()
                
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.horizontal)
            
            Spacer()
        }
        .navigationTitle("")
        .navigationBarHidden(true)
        .enableSwipeBackGesture()
        .onAppear {
            // 订阅用户信息消息
            socketManager.subscribeToAirInfo()
                .receive(on: DispatchQueue.main)
                .sink {  info in
                    airInfo = info
                    self.windMode = airInfo?.windmode ?? 0
                    self.windStrength = airInfo?.airvolume ?? 0
                    let unit = airInfo?.airunit
                    self.selectedUnit = unit == 0 ? .celsius: .fahrenheit
                    self.loopMode = airInfo?.loopmode ?? 0
                    self.autoMode = airInfo?.automode ?? 0
                    self.airOpen = airInfo?.switchon ?? 0
                    self.compressor = airInfo?.compressor ?? 0
                    
                }
                .store(in: &cancellables)
            SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_AIR_INFO)
            startTimer()
        }
        .onDisappear{
            stopTimer()
        }
    }
    
    // 启动定时器
    private func startTimer() {
        isRunning = true
        // 创建定时器：每隔1秒发送一次信号，在主线程接收
        cancellable = Timer.publish(every: 5, on: .main, in: .common)
            .autoconnect()
            .sink { _ in
                // 每秒执行的任务
                print("定时器执行")
                SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_AIR_INFO)
            }
    }
    
    // 停止定时器
    private func stopTimer() {
        isRunning = false
        cancellable?.cancel() // 取消订阅
        cancellable = nil
    
    }
    
}

// 定义温度单位枚举
enum TemperatureUnit: String, CaseIterable, Identifiable {
    case celsius = "°C"
    case fahrenheit = "°F"
    
    var id: Self { self }
}

#Preview {
    AirConditionalView()
}
